# @Time : 2024-12-23 14:46
# @Author : Fioman 
# @Phone : 13149920693
"""
账户管理相关的viewmodel类,和账号管理相关的操作都是在这viewmodel中进行操作,
包括用户登录账户管理等
"""
from typing import Dict

from common.datetime_helper import get_now_str
from common.produce_logger import debug_produce
from db_tool.db_config import TableName
from db_tool.db_handler import DbHandler
from personal_tool.data_result import DataResult
from personal_tool.enum_data import Role

db = DbHandler()


class UserinfoManager(object):
    """
    用户信息管理类,包括账号添加,账号删除,修改等操作.
    还有登录
    """

    @staticmethod
    def login_from_web(userInfo):
        """
        前端界面
        :param self:
        :param userInfo:
        :return:
        """
        username = userInfo.get("username", None)
        password = userInfo.get("password", None)
        res = {
            "status": "error",
            "info": "",
            "currentAuthority": Role.User.value
        }
        if not username or not password:
            res["info"] = "用户名或者密码不能为空"
            return res

        if username == "admin" and password == "admin":
            res["status"] = "ok"
            res["currentAuthority"] = Role.Admin.value
            return res
        # 从数据库获取数据
        query = {
            "username": username,
            "password": password
        }
        userRes = db.get_data_one(TableName.userinfos, query)
        if userRes.state:
            res["status"] = "ok"
            res["currentAuthority"] = userRes.data.get("role")
            newValues = {
                "lastLoginTime": get_now_str()
            }
            # 登录成功,更新登录时间
            updateRes = db.update_data(TableName.userinfos, query, newValues)
            if not updateRes.state:
                debug_produce(f"数据库更新异常: {updateRes.info}")
            return res
        else:
            res["status"] = "error"
            res["info"] = "用户名或者密码错误,请重新输入"
            return res

    @staticmethod
    def get_userinfos_from_web() -> DataResult:
        """
        获取用户信息表
        :return:
        """
        return db.get_data_list(TableName.userinfos)

    @staticmethod
    def save_userinfo_from_web(userinfo: Dict) -> DataResult:
        """
        保存用户信息,界面上点击保存的时候,有可能是新增用户,有可能是保存旧用户
        @param userinfo:
        @return:
        """
        result = DataResult()
        # 首先保存的用户名不能是admin
        username = userinfo.get("username", None)
        if username == "admin":
            result.info = "用户名不能是admin,请重新操作"
            return result
        query = {
            "key": userinfo.get("key", None)
        }

        userRes = db.get_data_one(TableName.userinfos, query)
        # 修改已存在用户信息
        if userRes.state:
            result = db.update_data(TableName.userinfos, query, userinfo)
        else:
            # 添加一个新用户,注意用户名不能重复
            query = {
                "username": username
            }
            # 如果有同名用户,就提示用户名已经存在
            userRes = db.get_data_one(TableName.userinfos, query)
            if userRes.state:
                result.info = f"用户名 {username} 已经存在,请重新操作"
                return result
            userinfo["registerTime"] = get_now_str()
            userinfo["lastLoginTime"] = "未登录"
            result = db.insert_data(TableName.userinfos, userinfo)

        return result

    @staticmethod
    def delete_userinfo_from_web(key: int) -> DataResult:
        """
        删除用户
        :param key:
        :return:
        """
        query = {
            "key": key
        }
        return db.delete_data(TableName.userinfos, query)
